package com.wuzao.ProxyPattern.third;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class GumballMachine extends UnicastRemoteObject implements GumballMachineRemote {

    State soldOutState;
    State noQuarterState;
    State hasQuarterState;
    State soldState;
    State state = null;
    String location;

    int count = 0;

    public GumballMachine(int numberGumballs,String location) throws RemoteException {
        super();
        this.location = location;
        soldOutState = new SoldOutState(this);
        noQuarterState = new NoQuarterState(this);
        hasQuarterState = new HasQuarterState(this);
        soldState = new SoldState(this);
        state = soldOutState;
        count = numberGumballs;
        if(count>0){
            state = noQuarterState;
        }
    }

    public void insertQuarter(){
        state.insertQuarter();
    }

    public void ejectQuarter(){
        state.ejectQuarter();
    }

    public void turnCrank(){
        state.turnCrank();
        state.dispense();
    }

    void setState(State state){
        this.state = state;
    }

    void releaseBall(){
        System.out.println("你获得一颗糖果了哦： 🍬 ");
        if(count!=0){
            count-=1;
        }
    }


    /**
     * 获得糖果机的库存
     * @return 库存
     * @throws RemoteException 远程调用异常
     */
    @Override
    public int getCount() throws RemoteException {
        return count;
    }

    /**
     * 获得糖果机的地址
     * @return 糖果机的地址
     * @throws RemoteException
     */
    @Override
    public String getLocation() throws RemoteException {
        return location;
    }

    @Override
    public State getState() throws RemoteException {
        return state;
    }
}
